package com.asiainfo.dbConnect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @Author yangyf
 * @Date 2021/7/13 0013 17:54
 * @Version 1.0
 * 配置文件
 */
public class ConfigParamsUtil {
    private final static Logger log = LoggerFactory.getLogger(ConfigParamsUtil.class);
    private final static String CONFIG_FILE_NAME = "config.properties";
    private static Properties properties;
    static {
        log.info("加载配置文件config.properties,配置文件位置: " + System.getProperty("flushConfigPath"));
        String config_path = System.getProperty("flushConfigPath");
        properties = new Properties();
        InputStream in = null;
        // 加载配置文件优先使用传参的配置文件
        try {
            if(config_path != null && !"".equals(config_path)){
                in = new FileInputStream(new File(config_path,CONFIG_FILE_NAME));
            }else{
                in = ConfigParamsUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
            }
            // 防止中文乱码
            properties.load(new InputStreamReader(in, "UTF-8"));
        } catch (IOException e) {
            log.error("加载config.properties配置文件出错！");
            e.printStackTrace();
        }
    }


    public static void init(String dbName){
        log.info("当前连接的数据库为：" + dbName);
        try {
            Field[] fields = ConfigParams.class.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                Class type = field.getType();
                String val_tmp = getProperty(dbName + "." + fieldName);
                // 当配置文件中没有设置则使用默认值
                if(val_tmp != null && !"".equals(val_tmp)){
                    Object val = ConvertVal(type,val_tmp);
                    field.set(null,val);
                }
            }
        } catch (Exception e) {
            log.error("动态将config.properties配置文件中的值赋给ConfigParams出错！");
            e.printStackTrace();
        }

    }

    /**
     * 配置文件参数获取
     * @param key
     * @return
     */
    public static String getProperty(String key){
        return properties.getProperty(key);
    }

    /**
     * 转换属性类型
     * @param type
     * @param val
     * @return
     */
    public static Object ConvertVal(Class type,String val){
        String simpleType = type.getSimpleName();
        if("Integer".equals(simpleType)){
            return Integer.parseInt(val);
        }else if("long".equals(simpleType)){
            return Long.parseLong(val);
        }else if("String".equals(simpleType)){
            return val;
        }else if("String[]".equals(simpleType)){
            return val.split(",");
        }
        return val;
    }
}
